package com.wad.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.wad.entity.system.SysUser;
import com.wad.utils.AuthContextUtil;
import com.wad.vo.common.Result;
import com.wad.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author wad
 * @date 2023/11/30 14:06
 * @project e-commerce
 **/

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求方式
        //如果当前请求方式是options，预检请求，直接放行
        String method = request.getMethod();
        if ("options".toUpperCase().equals(method)){
            return true;
        }
        //从请求头中获取token
        String token = request.getHeader("token");
        //如果token为空，返回错误提示
        if (StrUtil.isEmpty(token)){
            responseNoLoginInfo(response);
            return false;
        }
        //如果token不为空，拿着token去查redis
        String userInfoString = redisTemplate.opsForValue().get("user:login" + token);
        //如果redis中查询不到，就返回错误提示
        if (StrUtil.isEmpty(userInfoString)){
            responseNoLoginInfo(response);
            return false;
        }
        //如果redis中查到数据，把用户信息放到ThreadLocal中
        AuthContextUtil.set(JSON.parseObject(userInfoString, SysUser.class));
        //把redis用户信息的数据更新过期时间
        redisTemplate.expire("user:login"+token,30, TimeUnit.MINUTES);
        //放行
        return true;
    }


    //返回208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response){
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter printWriter=null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        try {
             printWriter = response.getWriter();
             printWriter.write(JSON.toJSONString(result));
        }catch (IOException exception){
            exception.printStackTrace();
        }finally {
            if (Objects.nonNull(printWriter)){
                printWriter.close();
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除ThreadLocal中的数据进行移除
        AuthContextUtil.remove();

    }
}
